<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="knn," />





  <link rel="alternate" href="/blog/atom.xml" title="稻草人的编程之路" type="application/atom+xml" />






<meta name="description" content="K近邻算法（KNN）什么是K近邻呢？它是机器学习中一个非常简单的算法，在理论上也是比较成熟的方法，计算与待评估指标最相近的K个数据，然后计算平均值 熟悉数据这里使用 airbnb 密码:0su1 的房屋租用情况为例来学习KNN算法  该数据集中包含有很多指标，这里我们只取其中几个指标  123456import pandas as pddata = pd.read_csv(&apos;listings.cs">
<meta name="keywords" content="knn">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习之knn">
<meta property="og:url" content="https://wangxiaochuang.github.io/2018/10/05/1.html">
<meta property="og:site_name" content="稻草人的编程之路">
<meta property="og:description" content="K近邻算法（KNN）什么是K近邻呢？它是机器学习中一个非常简单的算法，在理论上也是比较成熟的方法，计算与待评估指标最相近的K个数据，然后计算平均值 熟悉数据这里使用 airbnb 密码:0su1 的房屋租用情况为例来学习KNN算法  该数据集中包含有很多指标，这里我们只取其中几个指标  123456import pandas as pddata = pd.read_csv(&apos;listings.cs">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-07T22:36:29.352Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习之knn">
<meta name="twitter:description" content="K近邻算法（KNN）什么是K近邻呢？它是机器学习中一个非常简单的算法，在理论上也是比较成熟的方法，计算与待评估指标最相近的K个数据，然后计算平均值 熟悉数据这里使用 airbnb 密码:0su1 的房屋租用情况为例来学习KNN算法  该数据集中包含有很多指标，这里我们只取其中几个指标  123456import pandas as pddata = pd.read_csv(&apos;listings.cs">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangxiaochuang.github.io/2018/10/05/1.html"/>





  <title>机器学习之knn | 稻草人的编程之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">稻草人的编程之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">众人皆醉我独醒 举世皆浊我独清</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangxiaochuang.github.io/blog/2018/10/05/1.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jackstraw">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="稻草人的编程之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">机器学习之knn</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-05T12:40:00+00:00">
                2018-10-05
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/knn/" itemprop="url" rel="index">
                    <span itemprop="name">knn</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/10/05/1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/10/05/1.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/10/05/1.html" class="leancloud_visitors" data-flag-title="机器学习之knn">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="K近邻算法（KNN）"><a href="#K近邻算法（KNN）" class="headerlink" title="K近邻算法（KNN）"></a>K近邻算法（KNN）</h1><p>什么是K近邻呢？它是机器学习中一个非常简单的算法，在理论上也是比较成熟的方法，计算与待评估指标最相近的K个数据，然后计算平均值</p>
<h2 id="熟悉数据"><a href="#熟悉数据" class="headerlink" title="熟悉数据"></a>熟悉数据</h2><p>这里使用 <a href="https://pan.baidu.com/s/1T46gPSDuPbogR16qeL3Z_w">airbnb 密码:0su1</a> 的房屋租用情况为例来学习KNN算法</p>
<ol>
<li>该数据集中包含有很多指标，这里我们只取其中几个指标</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line">data = pd.read_csv(<span class="string">'listings.csv'</span>)</span><br><span class="line">features = [<span class="string">'accommodates'</span>, <span class="string">'bedrooms'</span>, <span class="string">'bathrooms'</span>, <span class="string">'beds'</span>, <span class="string">'price'</span>, <span class="string">'minimum_nights'</span>, <span class="string">'maximum_nights'</span>, <span class="string">'number_of_reviews'</span>]</span><br><span class="line">data = data[features]</span><br><span class="line">print(data.shape)       </span><br><span class="line">data.head()             <span class="comment"># 看下数据都有什么</span></span><br></pre></td></tr></table></figure>
<ol>
<li><p>指标释义：</p>
<ol>
<li>accommodates         可以容纳的旅客数量</li>
<li>bedrooms             卧室的数量</li>
<li>bathrooms            厕所的数量</li>
<li>beds                 床的数量</li>
<li>price                每晚的费用</li>
<li>minimum_nights       客人最少租了几天</li>
<li>maximum_nights       客人最多租了几天</li>
<li>number_of_reviews    评论数</li>
</ol>
</li>
</ol>
<h2 id="试验（基础篇）"><a href="#试验（基础篇）" class="headerlink" title="试验（基础篇）"></a>试验（基础篇）</h2><h3 id="提出问题"><a href="#提出问题" class="headerlink" title="提出问题"></a>提出问题</h3><p>假设现在我们有一个房子有3个房间，那么我们要租多少钱呢？思路：选择与我们的房间个数最近（可能是2个或4个房间）的K个数据，求平均价格</p>
<p>实现步骤：</p>
<ol>
<li>计算房间个数与我们自己的房间数3的距离（直接相减即为距离）</li>
<li>按距离从小到大排序</li>
<li>取前K个数据的价格求平均值即为预测结果</li>
</ol>
<p>这里提到了距离，但是说的是一个指标，我们的数据大部分情况下是多个指标的，那么如何来计算多个指标的距离呢？</p>
<script type="math/tex; mode=display">
d = \sqrt {(q_1 - p_1)^2 + (q_2 - p_2)^2 + {\cdots} + (q_n - p_n)^2}</script><p>只要是能够计算的指标，都是可以用欧式距离来计算</p>
<h4 id="只针对房间个数进行计算（单指标）"><a href="#只针对房间个数进行计算（单指标）" class="headerlink" title="只针对房间个数进行计算（单指标）"></a>只针对房间个数进行计算（单指标）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 添加一个指标distance，用于存储房间个数的距离</span></span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">our_acc_value = <span class="number">3</span>       <span class="comment"># 设置待预测的房间个数</span></span><br><span class="line">data[<span class="string">'distance'</span>] = np.abs(data.accommodates - our_acc_value)</span><br><span class="line">data.distance.value_counts().sort_index()   <span class="comment"># 根据结果可以看到距离为0的有461个，说明有461个样本的房间个数为3，我们从中取K个求平均值</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 洗牌与排序的操作</span></span><br><span class="line">data = data.sample(frac=<span class="number">1</span>, random_state=<span class="number">0</span>)  <span class="comment"># 为了消除数据样本间可能的关联，对数据进行一个洗牌的操作</span></span><br><span class="line">data = data.sort_values(<span class="string">'distance'</span>)         <span class="comment"># 是否有在想，既然都排序了，洗牌操作有用么？当然有用，这里排序是根据distance排序的，相同的distance的记录的顺序是可以打乱的</span></span><br><span class="line">data.price.head()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 计算前K个记录的均值</span></span><br><span class="line">data[<span class="string">'price'</span>] = data.price.str.replace(<span class="string">"\$|,"</span>, <span class="string">''</span>).astype(float)    <span class="comment"># 样本中的价格字段是字符串，且包含特殊符号</span></span><br><span class="line">mean_price = data.price.iloc[:<span class="number">5</span>].mean()</span><br><span class="line">print(mean_price)</span><br></pre></td></tr></table></figure>
<h3 id="解决问题"><a href="#解决问题" class="headerlink" title="解决问题"></a>解决问题</h3><p>通过上面的分析，我们已经知道了knn的原理，同时也能够根据某个指标来计算价格，但是计算出来后到底怎么样，我们需要有个模型评估的过程</p>
<p>这里我们将数据的75%分为训练集，25%分为测试集</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">data.drop(<span class="string">'distance'</span>, axis=<span class="number">1</span>)       <span class="comment"># 删除之前计算的distance</span></span><br><span class="line">train_df = data.copy().iloc[:<span class="number">2792</span>]</span><br><span class="line">test_df = data.copy().iloc[<span class="number">2792</span>:]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">predict_price</span><span class="params">(new_listing_value, features_column)</span>:</span></span><br><span class="line">    temp_df = train_df</span><br><span class="line">    temp_df[<span class="string">'distance'</span>] = np.abs(data[features_column] - new_listing_value)</span><br><span class="line">    temp_df = temp_df.sort_values(<span class="string">'distance'</span>)</span><br><span class="line">    knn_5 = temp_df.price.iloc[:<span class="number">5</span>]</span><br><span class="line">    predicted_price = knn_5.mean()</span><br><span class="line">    <span class="keyword">return</span> predicted_price</span><br><span class="line"></span><br><span class="line"><span class="comment"># 计算测试集的预测值，其是根据训练集的数据计算而来</span></span><br><span class="line"><span class="comment"># 这里的apply会将每个样本的accommodates值作为predict_price的第一个参数进行计算</span></span><br><span class="line">test_df[<span class="string">'predicted_price'</span>] = test_df.accommodates.apply(predict_price, features_column=<span class="string">'accommodates'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="模型评估"><a href="#模型评估" class="headerlink" title="模型评估"></a>模型评估</h3><p>通过上面的计算，我们能够非常方便的根据每个指标计算预测价格值，这里我们看看如何进行模型评估</p>
<h4 id="RMSE（root-mean-squared-error，均方根误差）"><a href="#RMSE（root-mean-squared-error，均方根误差）" class="headerlink" title="RMSE（root mean squared error，均方根误差）"></a>RMSE（root mean squared error，均方根误差）</h4><script type="math/tex; mode=display">
RMSE = \sqrt {\frac{(actual_1 - predicted_1)^2 + (actual_2 - predicted_2)^2 + \cdots + (actual_n - predicted_n)^2}{n}}</script><p>通过公式我们可以看到，这个公式计算了真实值与预测值间的差值，表达了模型是有多么不好，数值越大越不好，计算也是非常简单</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">test_df[<span class="string">'squared_error'</span>] = (test_df[<span class="string">'predicted_price'</span>] - test_df[<span class="string">'price'</span>]) ** <span class="number">2</span></span><br><span class="line">mse = test_df[<span class="string">'squared_error'</span>].mean()</span><br><span class="line">rmse = mse ** (<span class="number">1</span>/<span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<p>我们分别计算一下不同指标的rmse值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> feature <span class="keyword">in</span> [<span class="string">'accommodates'</span>, <span class="string">'bedrooms'</span>, <span class="string">'bathrooms'</span>, <span class="string">'number_of_reviews'</span>]:</span><br><span class="line">    test_df[<span class="string">'predicted_price'</span>] = test_df[feature].apply(predict_price, features_column=feature)</span><br><span class="line">    test_df[<span class="string">'squared_error'</span>] = (test_df[<span class="string">'predicted_price'</span>] - test_df[<span class="string">'price'</span>])**<span class="number">2</span></span><br><span class="line">    rmse = test_df[<span class="string">'squared_error'</span>].mean() ** (<span class="number">1</span>/<span class="number">2</span>)</span><br><span class="line">    print(<span class="string">"RMSE for the &#123;&#125; column: &#123;&#125;"</span>.format(feature, rmse))</span><br></pre></td></tr></table></figure>
<h2 id="进阶（多变量KNN模型）"><a href="#进阶（多变量KNN模型）" class="headerlink" title="进阶（多变量KNN模型）"></a>进阶（多变量KNN模型）</h2><p>在基础篇我们试验了计算一个指标的预测价格，同时也试验了如何评估模型好坏，确实也看到了差别。但是我们有多个指标，如何将它们统一结合起来完成我们的终极预测目标呢？</p>
<h3 id="数据预处理"><a href="#数据预处理" class="headerlink" title="数据预处理"></a>数据预处理</h3><p>为什么要进行数据预处理？</p>
<p>通过欧式距离，我们知道，要计算每个指标的差异，这样的计算会受原始数据性质的影响，取值比较大的数据天生比取值小的数据距离大</p>
<p>比如有房间个数和平方面积两个指标，如果不进行预处理，面积的影响将大于房间个数，但是我们并没有这样的假设，因此我们需要消除这种问题</p>
<h4 id="标准化（standardization-或-Z-score-normalization）"><a href="#标准化（standardization-或-Z-score-normalization）" class="headerlink" title="标准化（standardization 或 Z-score normalization）"></a>标准化（standardization 或 Z-score normalization）</h4><p>让我们的数据形成一个新的分布（均值为0，标准差为1的分布）</p>
<script type="math/tex; mode=display">
z = \frac {x - \mu}{\sigma}</script><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> preprocessing</span><br><span class="line">std_scale = preprocession.StandardScaler().fit(df)</span><br></pre></td></tr></table></figure>
<h4 id="归一化（Min-Max-scaling-或-normalization）"><a href="#归一化（Min-Max-scaling-或-normalization）" class="headerlink" title="归一化（Min-Max scaling 或 normalization）"></a>归一化（Min-Max scaling 或 normalization）</h4><p>将我们所有特征的值压缩到0到1的区间上，这样做还可以抑制离群值对结果的影响</p>
<script type="math/tex; mode=display">
X_{norm} = \frac {X - X_{min}}{X_{max} - X_{min}}</script><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> preprocessing</span><br><span class="line">minmax_scale = preprocession.MinMaxScaler().fit(df)</span><br></pre></td></tr></table></figure>
<h3 id="重新处理我们的listing数据"><a href="#重新处理我们的listing数据" class="headerlink" title="重新处理我们的listing数据"></a>重新处理我们的listing数据</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> StandardScaler</span><br><span class="line">features = [<span class="string">'accommodates'</span>, <span class="string">'bedrooms'</span>, <span class="string">'bathrooms'</span>, <span class="string">'beds'</span>, <span class="string">'price'</span>, <span class="string">'minimum_nights'</span>, <span class="string">'maximum_nights'</span>, <span class="string">'number_of_reviews'</span>]</span><br><span class="line">data = pd.read_csv(<span class="string">'listings.csv'</span>)</span><br><span class="line">data = data[features]</span><br><span class="line">data[<span class="string">'price'</span>] = data.price.str.replace(<span class="string">"\$|,"</span>, <span class="string">""</span>).astype(float)</span><br><span class="line">data = data.dropna()        <span class="comment"># 直接删除有缺失值的记录</span></span><br><span class="line">data[features] = StandardScaler().fit_transform(data[features])</span><br><span class="line">normalized_data = data</span><br></pre></td></tr></table></figure>
<h3 id="开始多变量欧式距离计算"><a href="#开始多变量欧式距离计算" class="headerlink" title="开始多变量欧式距离计算"></a>开始多变量欧式距离计算</h3><p><strong>使用scipy计算欧式距离</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> scipy.spatial <span class="keyword">import</span> distance</span><br><span class="line">first_data = normalized_data.iloc[<span class="number">0</span>][[<span class="string">'accommodates'</span>, <span class="string">'bathrooms'</span>]]</span><br><span class="line">fifth_data = normalized_data.iloc[<span class="number">20</span>][[<span class="string">'accommodates'</span>, <span class="string">'bathrooms'</span>]]</span><br><span class="line">first_fifth_distance = distance.euclidean(first_data, fifth_data)</span><br></pre></td></tr></table></figure>
<p>多个变量参与预测价格</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">norm_train_df = normalized_data.copy().iloc[:<span class="number">2792</span>]</span><br><span class="line">norm_test_df = normalized_data.copy().iloc[<span class="number">2792</span>:]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">predict_price_multivariate</span><span class="params">(new_listing_value, feature_columns)</span>:</span></span><br><span class="line">    temp_df = norm_train_df</span><br><span class="line">    temp_df[<span class="string">'distance'</span>] = distance.cdist(temp_df[feature_columns], [new_listing_value[feature_columns]])</span><br><span class="line">    temp_df = temp_df.sort_values(<span class="string">'distance'</span>)</span><br><span class="line">    knn_5 = temp_df.price.iloc[:<span class="number">5</span>]</span><br><span class="line">    predicted_price = knn_5.mean()</span><br><span class="line">    <span class="keyword">return</span> predicted_price</span><br><span class="line"></span><br><span class="line">cols = [<span class="string">'accommodates'</span>, <span class="string">'bathrooms'</span>]</span><br><span class="line">norm_test_df[<span class="string">'predicted_price'</span>] = norm_test_df[cols].apply(predict_price_multivariate, feature_columns=cols, axis=<span class="number">1</span>)</span><br><span class="line">norm_test_df[<span class="string">'squared_error'</span>] = (norm_test_df[<span class="string">'predicted_price'</span>] - norm_test_df[<span class="string">'price'</span>]) ** <span class="number">2</span></span><br><span class="line">rmse = norm_test_df[<span class="string">'squared_error'</span>].mean() ** (<span class="number">1</span>/<span class="number">2</span>)</span><br><span class="line">print(rmse)</span><br></pre></td></tr></table></figure>
<h3 id="使用Sklearn来完成KNN"><a href="#使用Sklearn来完成KNN" class="headerlink" title="使用Sklearn来完成KNN"></a>使用Sklearn来完成KNN</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.neighbors <span class="keyword">import</span> KNeighborsRegressor</span><br><span class="line">cols = [<span class="string">'accommodates'</span>, <span class="string">'bathrooms'</span>]            <span class="comment"># 可以选择多个指标</span></span><br><span class="line">knn = KNeighborsRegressor(n_neighbors=<span class="number">5</span>)        <span class="comment"># k的值，默认为5，可省略</span></span><br><span class="line">knn.fit(norm_train_df[cols], norm_train_df[<span class="string">'price'</span>])</span><br><span class="line">two_features_predictions = knn.predict(norm_test_df[cols])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 计算rmse</span></span><br><span class="line"><span class="keyword">from</span> sklearn.metrics <span class="keyword">import</span> mean_squared_error</span><br><span class="line">two_features_mse = mean_squared_error(norm_test_df[<span class="string">'price'</span>], two_features_predictions)</span><br><span class="line">two_features_rmse = two_features_mse ** (<span class="number">1</span>/<span class="number">2</span>)</span><br><span class="line">print(two_features_rmse)</span><br></pre></td></tr></table></figure>
<h2 id="knn优缺点"><a href="#knn优缺点" class="headerlink" title="knn优缺点"></a>knn优缺点</h2><h3 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h3><p>由于要计算出最小距离，因此需要与每条数据进行比对，当数据非常大的时候会非常慢</p>
<h3 id="优点"><a href="#优点" class="headerlink" title="优点"></a>优点</h3><p>knn不需要训练模型，直接用即可</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/knn/" rel="tag"># knn</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/09/20/1.html" rel="next" title="数据分析之seaborn">
                <i class="fa fa-chevron-left"></i> 数据分析之seaborn
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/10/14/1.html" rel="prev" title="mathjax">
                mathjax <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="jackstraw" />
            
              <p class="site-author-name" itemprop="name">jackstraw</p>
              <p class="site-description motion-element" itemprop="description">人生的意义，不在于最终获得了什么，而在于曾经努力追求过什么</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#K近邻算法（KNN）"><span class="nav-number">1.</span> <span class="nav-text">K近邻算法（KNN）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#熟悉数据"><span class="nav-number">1.1.</span> <span class="nav-text">熟悉数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#试验（基础篇）"><span class="nav-number">1.2.</span> <span class="nav-text">试验（基础篇）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#提出问题"><span class="nav-number">1.2.1.</span> <span class="nav-text">提出问题</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#只针对房间个数进行计算（单指标）"><span class="nav-number">1.2.1.1.</span> <span class="nav-text">只针对房间个数进行计算（单指标）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#解决问题"><span class="nav-number">1.2.2.</span> <span class="nav-text">解决问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模型评估"><span class="nav-number">1.2.3.</span> <span class="nav-text">模型评估</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#RMSE（root-mean-squared-error，均方根误差）"><span class="nav-number">1.2.3.1.</span> <span class="nav-text">RMSE（root mean squared error，均方根误差）</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#进阶（多变量KNN模型）"><span class="nav-number">1.3.</span> <span class="nav-text">进阶（多变量KNN模型）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据预处理"><span class="nav-number">1.3.1.</span> <span class="nav-text">数据预处理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#标准化（standardization-或-Z-score-normalization）"><span class="nav-number">1.3.1.1.</span> <span class="nav-text">标准化（standardization 或 Z-score normalization）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#归一化（Min-Max-scaling-或-normalization）"><span class="nav-number">1.3.1.2.</span> <span class="nav-text">归一化（Min-Max scaling 或 normalization）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#重新处理我们的listing数据"><span class="nav-number">1.3.2.</span> <span class="nav-text">重新处理我们的listing数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#开始多变量欧式距离计算"><span class="nav-number">1.3.3.</span> <span class="nav-text">开始多变量欧式距离计算</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用Sklearn来完成KNN"><span class="nav-number">1.3.4.</span> <span class="nav-text">使用Sklearn来完成KNN</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#knn优缺点"><span class="nav-number">1.4.</span> <span class="nav-text">knn优缺点</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#缺点"><span class="nav-number">1.4.1.</span> <span class="nav-text">缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优点"><span class="nav-number">1.4.2.</span> <span class="nav-text">优点</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jackstraw</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'lQM75w94ggNR0TjX61NLerrg-gzGzoHsz',
        appKey: 'I2wtQ2rd9KtoJmcEOiYG9zqT',
        placeholder: '如需帮助，请留下邮箱',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
    var infoEle = document.querySelector('#comments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lQM75w94ggNR0TjX61NLerrg-gzGzoHsz", "I2wtQ2rd9KtoJmcEOiYG9zqT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
